/*
 * @Author: i@douxuefeng.cn
 * @Date: 2021-12-18 18:14:50
 * @LastEditTime: 2021-12-18 18:14:52
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: \mountain\utils\functions.go
 */
package utils

import (
	"errors"

	comm "gitee.com/douxuefeng/go-utils"
	"github.com/kataras/iris/v12"
	"github.com/spf13/viper"
)

/**
 * @name: 获取用户id
 * @param {iris.Context} ctx
 * @return {*}
 */
func GetUser(ctx iris.Context) int64 {
	userId, _ := ctx.Values().GetInt64(viper.GetString("jwtUser"))
	return userId
}

/**
 * @name: 获取用户tokenId
 * @param {iris.Context} ctx
 * @return {*}
 */
func GetTokenId(ctx iris.Context) string {
	tokenId := ctx.Values().GetString(viper.GetString("jwtTokenId"))
	if len(tokenId) == 0 {
		ctx.JSON(comm.JsonErr(401, errors.New("登录信息错误，请重新登录")))
		ctx.StopExecution()
	}
	return tokenId
}

/**
 * @name: 获取分页
 * @param {iris.Context} ctx
 * @return {*}
 */
func GetPage(ctx iris.Context) (page, pageSize int) {
	page = ctx.URLParamIntDefault("page", 1)
	pageSize = ctx.URLParamIntDefault("page_size", viper.GetInt("page"))
	if page <= 0 || pageSize <= 0 {
		return 1, viper.GetInt("page")
	}
	return
}

/**
 * @name:  获取用户真实IP
 * @param {iris.Context} ctx
 * @return {*}
 */
func GetRealIP(ctx iris.Context) string {
	ip := ctx.GetHeader("X-Real-IP")
	if len(ip) == 0 {
		return ctx.RemoteAddr()
	}
	return ip
}
